package com.example.administrator.yunniuusedcar.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.administrator.common.base.BaseActivity;
import com.example.administrator.common.base.Global;
import com.example.administrator.common.utils.RegxUtils;
import com.example.administrator.yunniuusedcar.R;
import com.example.administrator.yunniuusedcar.model.mode_benn.IHttpService;
import com.example.administrator.yunniuusedcar.model.mode_benn.huiYuanBean.HuiYuanZC_regBean;
import com.example.administrator.yunniuusedcar.model.mode_benn.huiYuanBean.getValidateCode_ShouJi_Bean;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 立即注册
 * Created by USER2015 on 2017/12/24.
 */

public class RegistrationActivity extends BaseActivity {


    public int zCcode;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.view7)
    View view7;
    @BindView(R.id.LL_title)
    RelativeLayout LLTitle;
    @BindView(R.id.et_NickName)
    EditText etNickName;
    @BindView(R.id.et_iPhoneNum)
    EditText etIPhoneNum;
    @BindView(R.id.et_YanZhengCode)    //验证码
            EditText etYanZhengCode;
    @BindView(R.id.et_InvitationCode)    // 邀请码
            EditText etInvitationCode;
    @BindView(R.id.tv_JingYanZhi)
    TextView tvJingYanZhi;
    @BindView(R.id.et_LoginPassWords)
    EditText etLoginPassWords;
    @BindView(R.id.et_AgainLoginPassWords)
    EditText etAgainLoginPassWords;
    @BindView(R.id.tv_HuiYuanZJ)
    TextView tvHuiYuanZJ;               //
    @BindView(R.id.iv_sellCarPagerZC)
    Button btnStartComputeZC;
    @BindView(R.id.btn_getYZcode)
    Button btnGetYZcode;
    private String loginPW;
    private String iPhoneNum;
    public int yZcode;
    private String huiYuan_id;


    @Override


    public int getLayoutRes() {
        return R.layout.activity_register;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
    }

    @Override
    public void initListener() {

    }

    @Override
    public void initData() {
        tel_key_val = android.provider.Settings.Secure.getString(getApplication().getContentResolver(),
                android.provider.Settings.Secure.ANDROID_ID);
    }

    @OnClick({R.id.iv_back, R.id.et_YanZhengCode, R.id.tv_JingYanZhi, R.id.tv_HuiYuanZJ,
            R.id.iv_sellCarPagerZC, R.id.btn_getYZcode
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.et_YanZhengCode:
                break;
            case R.id.tv_JingYanZhi:
                break;
            case R.id.btn_getYZcode:   //获取验证码
                //获取验证码
                if (!"".equals(etIPhoneNum.getText().toString().trim())) {

                    String etIPhoneNum1 = etIPhoneNum.getText().toString();

                    getYZcode(etIPhoneNum1);

                } else {
                    Toast.makeText(RegistrationActivity.this, "手机号不能为空", Toast.LENGTH_SHORT).show();

                };
                break;

            case R.id.tv_HuiYuanZJ:
                break;
            case R.id.iv_sellCarPagerZC:  // 注册

                if (!"".equals(etNickName.getText().toString()) && !"".equals(etIPhoneNum.getText().toString()) &&
                         // !"".equals(etYanZhengCode.getText().toString()) &&
                        !"".equals(etLoginPassWords.getText().toString()) &&
                        !"".equals(etAgainLoginPassWords.getText().toString().trim()) ) {

                    String NickName = etNickName.getText().toString();  // 昵称
                    String iPhoneNum = etIPhoneNum.getText().toString();    //手机号
                    String yzMcode = etYanZhengCode.getText().toString(); /// 验证码
                    String YCode = etInvitationCode.getText().toString();     // 邀请码？
                    String loginPW = etLoginPassWords.getText().toString();   // 登录密码
                    String AgainLoginPW = etAgainLoginPassWords.getText().toString();    // 确认密码

                    String HuiYuanYanZ = tvHuiYuanZJ.getText().toString();

                    RexUP(NickName, iPhoneNum, yzMcode, YCode, loginPW, AgainLoginPW);
                } else {
                    Global.showToast("您填写的数据不一致，请检查数据！");
                }
                break;
        }
    }

    String tel_key_val="";
    private void getYZcode(String etIPhoneNum1) {  //获取手机验证码
        final String ul1 = IHttpService.HOST_URL +"member/getValidateCode";
        tel_key_val = android.provider.Settings.Secure.getString(getApplication().getContentResolver(),
                android.provider.Settings.Secure.ANDROID_ID);

        OkHttpUtils.post().url(ul1).addParams("sign", IHttpService.SignVal).addParams("tel_key", tel_key_val).addParams("phone",etIPhoneNum1).build()
                .execute(new StringCallback() {

                    private int iphonCode;

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Global.showToast("获取手机验证码失败" + e);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Toast.makeText(getApplicationContext(),response,Toast.LENGTH_LONG).show();
                        //Global.showToast("获取手机验证码成功" + response);
                        getValidateCode_ShouJi_Bean iphonCodes = new Gson().fromJson(response, getValidateCode_ShouJi_Bean.class);
                        iphonCode = iphonCodes.data;  //验证码 （待判断）
                    }

                });
    }

//    private boolean checkInput1(String iPhoneNum, String loginPW, String yzMcode) {
//    if (TextUtils.isEmpty(iPhoneNum)) { // 电话号码为空
//        Global.showShort(this, R.string.tip_phone_can_not_be_empty);
//    } else {
//        if (!RegxUtils.checkMobile(iPhoneNum)) { // 电话号码格式有误
//            Global.showShort(this, R.string.tip_phone_regex_not_right);
//        } else if (TextUtils.isEmpty(yzMcode)) { // 验证码不正确
//            Global.showShort(this, R.string.tip_please_input_code);
//        } else if (loginPW.length() < 6 || loginPW.length() > 32
//                || TextUtils.isEmpty(loginPW)) { // 密码格式
//            Global.showShort(this,
//                    R.string.tip_please_input_6_32_password);
//        } else {
//            return true;
//        }
//    }
//
//    return false;
//}

    //   private boolean checkInput(String etIPhoneNum, String IPhoneNum, String YZCode) {
//    if (TextUtils.isEmpty(etIPhoneNum)) { // 电话号码为空
//        RegxUtils.showShort(this, R.string.tip_phone_can_not_be_empty);
//    } else {
//        if (!RegexUtils.checkMobile(phone)) { // 电话号码格式有误
//            ToastUtils.showShort(this, R.string.tip_phone_regex_not_right);
//        } else if (TextUtils.isEmpty(code)) { // 验证码不正确
//            ToastUtils.showShort(this, R.string.tip_please_input_code);
//        } else if (password.length() < 6 || password.length() > 32
//                || TextUtils.isEmpty(password)) { // 密码格式
//            ToastUtils.showShort(this,
//                    R.string.tip_please_input_6_32_password);
//        } else {
//            return true;
//        }
//    }
//
//    return false;
//}

//    private void getYZcode(final EditText etIPhoneNum) {  // 验证码
//        final String ul2 = IHttpService.HOST_URL + "Sign/getTocken";    // 获取sign值
//        final String tel_val = "33333333333333333";
//        OkHttpUtils.post().url(ul2).addParams("tel_key", tel_val).build().execute(new StringCallback() {     //.addParams("type","1")     222222222222222
//
//            @Override
//            public void onError(Call call, Exception e, int id) {
//                Global.showToast("请求超时！" + e.getMessage());
//                System.out.println("-----====----------A" + e);
//            }
//
//            @Override
//            public void onResponse(String response, int id) {
//                System.out.println("-----====----------A1" + response.toString());
//
//
//                TOKEN mTOKEN = new Gson().fromJson(response, TOKEN.class);
//
//                if (mTOKEN.getCode() == 1) {
//                    String ul = IHttpService.HOST_URL + "member/getValidateCode";    // 手机验证
//
//                    OkHttpUtils.post().url(ul).addParams("sign", mTOKEN.getData()).addParams("tel_key", tel_val).addParams("phone", String.valueOf(etIPhoneNum)).build().execute(new StringCallback() {
//                        @Override
//                        public void onError(Call call, Exception e, int id) {
//                            Global.showToast("请求超时！" + e.getMessage());
//                            System.out.println("-----====----------A" + e);
//                        }
//
//                        @Override
//                        public void onResponse(String response, int id) {
//                            System.out.println("-----====----------A" + response.toString());
//                            Global.showToast("成功" + response);
//                            getValidateCode_ShouJi_Bean MYZcode = new Gson().fromJson(response, getValidateCode_ShouJi_Bean.class);
//
//                            yZcode = MYZcode.data;  //手机验证吗
//                            if (MYZcode.code == 1) {
////                                //登陆成功，跳转
////                                Intent intent = new Intent(UserLoginActivity.this, MainActivity.class);
////                                intent.putExtra("fragid", 5);
////                                android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
////                                transaction.replace(R.id.view_pager, new MineFragment5Model());
////                                startActivity(intent);
////
//                                Toast.makeText(RegistrationActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();
//                            } else {
//                                //登录失败
//                            }
//                        }
//                    });
//
////                WZ_ArticleInfoBean wzArticleInfoBean = new Gson().fromJson(response, WZ_ArticleInfoBean.class);
//                } else {
//                    Global.showToast("网络繁忙，请稍后再试");
//
////                    //请求失败
//                }
//            }
//        });
//    }

    private void RexUP(final String nickName, final String iPhoneNum, final String iphonCode,
                       final String YCode, final String loginPW, final String againLoginPW) {

        final String ul2 = IHttpService.HOST_URL +"member/reg";
        OkHttpUtils.post().url(ul2).addParams("sign",IHttpService.SignVal)
                .addParams("tel_key",tel_key_val).addParams("code",iphonCode)
                .addParams("nicke", nickName).addParams("phone", iPhoneNum)
                .addParams("password", loginPW) .addParams("repassword", againLoginPW).build().execute(new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                String e_str = e.toString();
                try {
                    JSONObject jsonObject= new JSONObject(e.toString());
                    if(jsonObject.getString("code").equals("1")){
                        Intent intent = new Intent(RegistrationActivity.this, UserLoginActivity.class);
                        startActivity(intent);
                        RegistrationActivity.this.finish();
                    }
                } catch (JSONException e1) {
                    Intent intent = new Intent(RegistrationActivity.this, UserLoginActivity.class);
                    startActivity(intent);
                    RegistrationActivity.this.finish();
                }
            }

            @Override
            public void onResponse(String response, int id) {


                Gson gson = new Gson();
                HuiYuanZC_regBean MZC = gson.fromJson(response, HuiYuanZC_regBean.class);


                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String data = jsonObject.getString("data");
                    Global.showToast(data);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                huiYuan_id = MZC.data;    // 获取会员id

                zCcode = MZC.code;  //状态吗
                if (MZC.code == 1) {
                    //登陆成功，跳转
                    Global.showToast("注册成功");
                    Intent intent = new Intent(RegistrationActivity.this, UserLoginActivity.class);
                    startActivity(intent);

                } else {
                    //登录失败
                }
            }
        });

    }


}
